package month4.day27;

import java.io.*;

public class S3 {
    public static void alterStringToROM(String oldString, String newString) {
        try {
            File file = new File("E:\\Java8\\新建文件夹\\java78.txt");
            long start = System.currentTimeMillis();
            BufferedReader br_File = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            CharArrayWriter caw = new CharArrayWriter();
            String string;
            int sum = 0;
            while ((string = br_File.readLine()) != null) {
                //判断是否包含目标字符，包含则替换
                if (string.contains(oldString)) {
                    string = string.replace(oldString, newString);
                    sum++;
                }
                //写入内容并添加换行
                caw.write(string);
                caw.write("\r\n");
            }
            br_File.close();
            BufferedWriter bw_File = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
            caw.writeTo(bw_File);
            caw.close();
            bw_File.close();
            long time = System.currentTimeMillis() - start;
            System.out.println(sum + "个" + oldString + "替换成" + newString + "耗费时间:" + time);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public static void main(String[] args) {
        String oldString = "金正恩";
        String newString = "金三胖";
        alterStringToROM(oldString, newString);
    }
}
